package com.athl.gulimall.product.exception;

import com.athl.common.exception.BizCodeEnum;
import com.athl.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author：易鑫
 * @Version：1.0
 * @Date：2022/5/17-13:39
 * @Since:jdk1.8
 * @Description:
 */

/**
 * 集中处理所有异常
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.athl.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {


    @ExceptionHandler(value = Throwable.class)
    public R handleExcetpion(Throwable throwable){
        return R.error(BizCodeEnum.UNKONW_EXCEPTON.getCode(),BizCodeEnum.UNKONW_EXCEPTON.getMsg());
    }


    /**
     * 处理数据校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{},异常类型:{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();

        Map<String,String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((item) -> {
//            getField()错误属性名字    getDefaultMessage()错误提示消息
            errorMap.put(item.getField(),item.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.UNKONW_EXCEPTON.getMsg()).put("data",errorMap);
    }

}
